// Copyright 2012 Google Inc. All Rights Reserved.

package com.google.appengine.syncserver.entities;

import com.google.appengine.api.datastore.Entity;

/**
 * Metadata class for shared preferences.
 */
public class PreferencesMetadata {

  // The properties key for storing max update version for shared preference.
  private static final String MAX_VERSION_KEY = "max_version";

  // The properties key for storing number of entities a shared preference has.
  private static final String NUMBER_OF_SHARDS_KEY = "no_of_shards";

  // Underlying datastore entity for metadata.
  private final Entity entity;

  /**
   * Constructor for shared preferences metadata.
   */
  public PreferencesMetadata(Entity entity) {
    this.entity = entity;
    if (!entity.hasProperty(MAX_VERSION_KEY)) {
      entity.setUnindexedProperty(MAX_VERSION_KEY, new Long(0));
    }
    if (!entity.hasProperty(NUMBER_OF_SHARDS_KEY)) {
      entity.setUnindexedProperty(NUMBER_OF_SHARDS_KEY, new Long(0));
    }
  }

  /**
   * @return The underlying Entity defining this class. 
   */
  public Entity getEntity() {
    return entity;
  }

  /**
   * @return Max update version of the shared preferences. 
   */
  public long getMaxVersion() {
    return (Long) entity.getProperty(MAX_VERSION_KEY);
  }

  /**
   * @return The number of parts the shared preferences is divided into.
   */
  public long getNumberOfParts() {
    return ((Long) entity.getProperty(NUMBER_OF_SHARDS_KEY));
  }

  /**
   * Sets the max update version number for the shared preferences.
   * 
   * @param version
   */
  public void setMaxVersion(long version) {
    entity.setUnindexedProperty(MAX_VERSION_KEY, version);
  }

  /**
   * Set the number of shards in the shared preferences.
   */
  public void setNumberOfParts(long numberOfParts) {
    entity.setUnindexedProperty(NUMBER_OF_SHARDS_KEY, numberOfParts);
  }
}
